package com.fingard.dsp.bank.directbank.cmb01;

import com.alibaba.fastjson.JSONObject;
import com.allinpay.ets.client.SecurityUtil;
import com.allinpay.ets.client.StringUtil;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.SendBankRespose;
import com.fingard.dsp.bank.directbank.allinpay02.AllInPay02Base;
import com.fingard.dsp.bank.directbank.allinpay02.AllInPay02Header;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.*;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.TreeMap;

public class CMB01Statement extends CMB01Base implements IStatement {
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        // 记账宝交易对账单
        String[] virtualOrderRespHeader = getVirtualOrderStatement(p_reqQrySttm, retAts);
        String virtualOrderTotalNum = retAts.totalNum;
        if ("".equals(virtualOrderTotalNum)) {
            virtualOrderTotalNum = "0";
        }

        if (virtualOrderRespHeader[0].equals("-1")) {
            String respInfo = "记账宝交易对账单获取失败,原因:[" + virtualOrderRespHeader[1] + "]";
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(respInfo);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = virtualOrderRespHeader[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            } else {
                // 获取成功时写入总笔数
                int totalNum = Integer.parseInt(virtualOrderTotalNum);
                retAts.isWritedTotalNum(String.valueOf(totalNum));
            }
        }

        retAts.writeEnd();
        return retAts;
    }


    private String[] getVirtualOrderStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};

        String respCode = "";
        String respInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;

        try {
            // 招行记账宝交易对账单获取
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTDTHQRY";
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommonHeader(xmlTextWriter, tmpBnkHeader);
            xmlTextWriter.writeStartElement("NTDTHQRYY");
            xmlTextWriter.writeElementString("ACCNBR", p_reqQrySttm.actNum);
            String qryFlag = getBankConfig().getValueAsString("qryFlag");
            if (StringHelper.hasAnyChar(qryFlag)) {
                xmlTextWriter.writeElementString("QRYFLG", qryFlag);
            } else {
                xmlTextWriter.writeElementString("QRYFLG", "1");
            }
            xmlTextWriter.writeElementString("DMANBR", "");
            xmlTextWriter.writeElementString("BEGDAT", Format.Date8Format.format(p_reqQrySttm.getBusDate()));
            xmlTextWriter.writeElementString("ENDDAT", Format.Date8Format.format(p_reqQrySttm.getBusDate()));
            xmlTextWriter.writeEndDocument();

            String[] resutlt = sendToBank(xmlTextWriter.toXmlString());

            if (resutlt[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String retCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD").trim();//返回码
                    String errMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");//返回信息
                    if ("0".equals(retCode)) {
                        respCode = "0";
                        while (tmpBkReader.read("/CMBSDKPGK/NTDTHQRYZ")) {
                            XElement readXElement = tmpBkReader.readedXElement;
                            RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                            tmpRetDetail.askNumber = readXElement.getSingleTextNotNull("TRXNBR");
                            tmpRetDetail.amount = readXElement.getSingleTextNotNull("TRXAMT");
                            String cur = readXElement.getSingleTextNotNull("CCYNBR");
                            tmpRetDetail.cur = getBankConfig().getMapKeyByValue("currencyMapping", cur);
                            String date = readXElement.getSingleTextNotNull("TRXDAT");
                            String time = readXElement.getSingleTextNotNull("TRXTIM");
                            tmpRetDetail.busTime = date + time;
                            tmpRetDetail.oppAct = readXElement.getSingleTextNotNull("RPYACC");
                            tmpRetDetail.oppActName = readXElement.getSingleTextNotNull("RPYNAM");
                            tmpRetDetail.bankOrderNo = readXElement.getSingleTextNotNull("NARINN");
                            tmpRetDetail.memo = readXElement.getSingleTextNotNull("TRXTXT");
                            String cdFlag = readXElement.getSingleTextNotNull("TRXDIR");
                            if ("D".equals(cdFlag)) {
                                tmpRetDetail.cdFlag = "27";
                            } else if ("C".equals(cdFlag)) {
                                tmpRetDetail.cdFlag = "22";
                            } else {
                                throw new Exception("无效的AMTCDR借贷标记：" + cdFlag);
                            }
                            tmpRetDetail.transState = TransState.Success;
                            retAts.writeRetDetail(tmpRetDetail);
                            totalNum++;
                        }
                    } else {
                        respCode = "-1";
                        respInfo = errMsg;
                    }
                } else {
                    respCode = "-1";
                    respInfo = tmpSbMsg.toString();
                }
            } else {
                respCode = "-1";
                respInfo = resutlt[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            respCode = "-1";
            respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = respCode;
        respHeader[1] = respInfo;

        return respHeader;
    }

}
